<script setup>
import { ref } from 'vue'
import { updatePassword } from '@/api/user.js'
import { ElMessage } from 'element-plus'
import { useTokenStore } from '@/stores/token.js'

const tokenStore = useTokenStore()

// 表单数据
const form = ref({
  oldPwd: '',
  newPwd: '',
  rePwd: ''
})

// 表单验证规则
const rules = {
  oldPwd: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
  newPwd: [{ required: true, message: '请输入新密码', trigger: 'blur' }],
  rePwd: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== form.value.newPwd) {
          callback(new Error('两次输入的新密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
}

// 提交表单
const onSubmit = async () => {
  try {
    const result = await updatePassword(form.value)
    if (result.code === 200) {
      ElMessage.success(result.message ? result.message : '密码更新成功')
      // 删除Token
      tokenStore.removeToken()
    } else {
      ElMessage.error(result.message ? result.message : '密码更新失败')
    }
  } catch (error) {
    ElMessage.error('更新密码失败，请稍后再试')
  }
}
</script>

<template>
  <el-card class="box-card">
    <h2>更新密码</h2>
    <el-form :model="form" :rules="rules" label-width="100px" size="large">
      <el-form-item label="旧密码" prop="oldPwd">
        <el-input v-model="form.oldPwd" type="password" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newPwd">
        <el-input v-model="form.newPwd" type="password" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="确认新密码" prop="rePwd">
        <el-input v-model="form.rePwd" type="password" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">更新密码</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<style scoped>
.box-card {
  max-width: 600px;
  margin: 20px auto;
  padding: 20px;
}
</style>
